#!/bin/bash
# base percona-toolkit-2.2.19

#def vars
DBNAME='db1'
DBUSER='xxx'
MONITOR_DBNAME='percona'
DBPASSWORD='xxxx'
DBHOST='10.10.10.11'
SLAVE_DBHOST='10.10.10.12'

MAXTABSIZE_MB=100

#init tmpfile
true > /tmp/pt-table-checksums.result
true > /tmp/pt-table-checksums.tmp

#get 
mysql -s -u${DBUSER} -p${DBPASSWORD} -h${DBHOST} ${DBNAME} > /tmp/pt-table-checksums.tmp <<EOF
SELECT 
    table_schema,
    TABLE_NAME,
    ROUND(SUM(DATA_LENGTH + INDEX_LENGTH) / POWER(1024, 2),
            2) mbs,
    SUM(TABLE_ROWS) table_rows,
    COUNT(*) cnt
FROM
    information_schema.TABLES
WHERE
    table_schema IN ("${DBNAME}")
--    and table_name='sync_test'
GROUP BY table_schema , TABLE_NAME
HAVING SUM(DATA_LENGTH + INDEX_LENGTH) / POWER(1024, 2) <= ${MAXTABSIZE_MB}
ORDER BY mbs DESC;

truncate table oz_market.checksums;
EOF

cat /tmp/pt-table-checksums.tmp |\
while read line; 
do 
  tabname=$(echo $line| awk '{print $2}')
  echo ${tabname};
  pt-table-checksum h="${DBHOST}",u="${DBUSER}",p="${DBPASSWORD}",P=3306 -d ${DBNAME} --tables=${tabname} --nocheck-replication-filters --replicate=oz_market.checksums --recursion-method=processlist >> /tmp/pt-table-checksums.result
done

diffcnt=$(awk '{print $3}' /tmp/pt-table-checksums.result | sort -d | uniq -c | grep -v DIFFS | awk '{print $2}' | grep -v 0 | wc -l)

mysql -s -u${DBUSER} -p${DBPASSWORD} -h${SLAVE_DBHOST} ${MONITOR_DBNAME} <<EOF
  insert into monitor_data_sync
  values(now(),${diffcnt});
  commit;
EOF

if [ $diffcnt -ne 0 ]
then
  echo warning
  python /root/DBAScripts/weixin.py linora datasyncerror datasyncerror${diffcnt}
fi